import { ref } from 'vue';

// 定义数据结构
interface AreaData {
  code: string;
  name: string;
  children?: AreaData[];
}

// 转换数据格式，适配Ant Design Vue的Cascader组件
const convertToAreaData = (data: any[]): AreaData[] => {
  if (!data || !Array.isArray(data)) {
    return [];
  }
  return data.map(item => ({
    code: item.value,
    name: item.label,
    children: item.children ? convertToAreaData(item.children) : undefined
  }));
};

// 安全地导入数据
let regionData: any[] = [];
let provinceAndCityData: any[] = [];
let regionDataPlus: any[] = [];
let provinceAndCityDataPlus: any[] = [];

try {
  // @ts-ignore
  const chinaAreaData = require('china-area-data');
  regionData = chinaAreaData.regionData || [];
  provinceAndCityData = chinaAreaData.provinceAndCityData || [];
  regionDataPlus = chinaAreaData.regionDataPlus || [];
  provinceAndCityDataPlus = chinaAreaData.provinceAndCityDataPlus || [];
} catch (error) {
  console.error('Failed to load china-area-data:', error);
}

// 导出完整的省市区数据（包含区县）
export const areaData = ref<AreaData[]>(convertToAreaData(regionData));

// 导出省市数据（不包含区县，加载更快）
export const provinceAndCityAreaData = ref<AreaData[]>(convertToAreaData(provinceAndCityData));

// 导出增强版数据（包含港澳台）
export const areaDataPlus = ref<AreaData[]>(convertToAreaData(regionDataPlus));
export const provinceAndCityAreaDataPlus = ref<AreaData[]>(convertToAreaData(provinceAndCityDataPlus));

// 提供选择器配置
export const cascaderConfig = {
  fieldNames: {
    label: 'name',
    value: 'code',
    children: 'children'
  },
  showSearch: true,
  placeholder: '请选择省市区',
  allowClear: true
};

/**
 * 根据编码获取完整地址名称
 */
export const getAreaNameByCode = (codes: string[], data: AreaData[] = areaData.value): string => {
  if (!codes || codes.length === 0) return '';
  
  let result = '';
  let currentData = data;
  
  for (let i = 0; i < codes.length; i++) {
    const code = codes[i];
    const item = currentData.find(d => d.code === code);
    if (item) {
      result += item.name;
      if (item.children) {
        currentData = item.children;
      }
    }
  }
  
  return result;
};

/**
 * 根据名称搜索区域
 */
export const searchAreaByName = (name: string, data: AreaData[] = areaData.value): AreaData[] => {
  const result: AreaData[] = [];
  
  const search = (items: AreaData[], keyword: string) => {
    items.forEach(item => {
      if (item.name.includes(keyword)) {
        result.push(item);
      }
      if (item.children) {
        search(item.children, keyword);
      }
    });
  };
  
  search(data, name);
  return result;
};

/**
 * 获取热门城市
 */
export const getHotCities = (): AreaData[] => {
  const hotCityCodes = [
    '110000', // 北京
    '120000', // 天津  
    '310000', // 上海
    '500000', // 重庆
    '440100', // 广州
    '440300', // 深圳
    '330100', // 杭州
    '320100', // 南京
    '420100', // 武汉
    '510100', // 成都
    '610100', // 西安
    '370100'  // 济南
  ];
  
  const hotCities: AreaData[] = [];
  
  areaData.value.forEach(province => {
    if (hotCityCodes.includes(province.code)) {
      hotCities.push(province);
    } else if (province.children) {
      province.children.forEach(city => {
        if (hotCityCodes.includes(city.code)) {
          hotCities.push(city);
        }
      });
    }
  });
  
  return hotCities;
};

// 兼容性导出（保持向后兼容）
export default areaData; 